package com.heima.app.config;

import com.heima.app.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @projectName: heima-leadnews
 * @package: com.heima.app.config
 * @className: MyGlobalFilter
 * @author: 躺着认真玩
 * @description: app端身份校验
 * @date: 2025/5/15 4:32
 * @version: 1.0
 */
@Component
public class MyGlobalFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    //     1获取请求和返回
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //     判断路径是否需要校验
        if (request.getURI().getPath().contains("/login")) {
            return chain.filter(exchange);
        }
    //     解析token
        String token = request.getHeaders().getFirst("token");
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i == 1 || i == 2) {
                //返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //     将token放到请求头中
            ServerHttpRequest newHeader = request.mutate().header("userId", claimsBody.get("id").toString()).build();
            return chain.filter(exchange.mutate().request(newHeader).build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    //     放行

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
